package servlet.lifecycle;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CounterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String file = null;
	private int counter;

	public void init() {
		file=getInitParameter("filePath");//servletConfig 관련 작업은 init 안이나 이후부터 사용가능!!!!!
		
		// file에 저장된 카운터 값을 읽어서counter변수에 할당.
		DataInputStream dis = null;

		try {
			// 1.연결 + filter 스트림(DataInputStream) 추가
			dis = new DataInputStream(new FileInputStream(file)); // 기존연결에
																	// DataInput스트림
																	// 추가.
			// 2. 입력작업
			// read할때 write 했던 순서대로 읽어야 한다.
			counter = dis.readInt(); // 4byte를 한번에 읽기 위해서

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (dis != null)
				try {
					dis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
	

	public void destroy() {
		// counter 변수의 값을 file에 출력

		boolean flag = false;

		DataOutputStream dos = null;
		try {

			dos = new DataOutputStream(new FileOutputStream(file));

			dos.writeInt(counter);

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		} finally {

			if (dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<html><head><title>카운터</title></head><body>");
		out.println("당신은" + ++counter + "번재 방문자입니다.");
		out.println("<p><a href ='index.html'>index.html로이동</a></p>");
		out.println("</body></html>");
	}

}
